# Copyright (c) 2024, cy080585@126.com and contributors
# For license information, please see license.txt

import frappe
# from frappe.model.document import Document
from frappe.utils import flt
import frappe.utils
from zy_packlist.zy_packlist.controllers.pack_listdoc import PackListDoc
from zy_packlist.zy_packlist.doctype.packing_list.packing_list import get_packing_items_ledgers,add_packing_items_ledgers

import frappe.data


class PackingProcess(PackListDoc):
    def before_save(self):
        super().before_save()
        total_amount=0.00
        for item in self.items:
            # if item.order_packing_list_item and not item.packing_list_items:
            # 	res=get_packing_items_ledgers(item.order_packing_list_item)
            # 	packing_list_doc=add_packing_items_ledgers(res,item,self)
            # 	item.packing_list_items=packing_list_doc.name
            # 	item.old_packing_list_items=packing_list_doc.name

            if item.old_packing_list_items and not item.packing_list_items and not item.order_packing_list_item:
                res=get_packing_items_ledgers(item.old_packing_list_items)
                packing_list_doc=add_packing_items_ledgers(res,item,self)
                item.packing_list_items=packing_list_doc.name
                item.old_packing_list_items=packing_list_doc.name
            total_amount+=item.amount or 0.00
        self.total_amount=total_amount
        self.order_total_amount=total_amount+flt(self.shipping_fee)

    def on_submit(self):
        super().on_submit()
        for item in self.items:
            if item.order_name:
                frappe.db.set_value('Packing Order',item.order_name,'status','Completed')

    def before_cancel(self):
        if self.total_amount_paid or self.is_freeze:
            frappe.throw("Total Payment Amount should be zero when cancelling the document or not be freeze.")

    def on_cancel(self):
        super().on_cancel()

        for item in self.items:
            if item.order_name:
                frappe.db.set_value('Packing Order',item.order_name,'status','Submitted')


    def on_trash(self):
        super().on_trash()
        for item in self.items:
            if item.order_name:
                frappe.db.set_value('Packing Order',item.order_name,'status','Submitted')

    def before_update_after_submit(self):
        if self.total_amount_paid  or  self.is_freeze:
             frappe.throw("Total Payment Amount should be zero when updating after submit of  the document  or not be freeze..")
        amount_changed=self.has_value_changed("items")
        if amount_changed:
            total_amount=0
            for item in self.items:
                total_amount+=item.amount
            self.total_amount=total_amount
            self.order_total_amount=total_amount+flt(self.shipping_fee)




@frappe.whitelist()
def get_packing_process_details(packing_name,as_dict=False):
	doc_status = frappe.db.get_value("Packing Process", packing_name, "docstatus")
	join_cloumn="packing_list_items"
	if doc_status == 2:
		join_cloumn='old_packing_list_items'

	sql=f"""
		SELECT tpoi.marks_no ,tpli.item_code ,tpli.item_name ,tpli.`size`,tpli.customs_item_code,tpli.qty,tpli.stock_uom,tpli.rate,tpli.amount,
		tpli.net_weight,tpoi.net_weight_pkg
		 ,tpoi.gross_weight_pkg,tpoi.packages_no,tpoi.carton_measure,tpoi.cbm
		FROM  `tabPacking Process Item` tpoi 
		left join `tabPacking Process` tpo  on tpoi.parent=tpo.name 
		left join `tabPacking List Item` tpli on tpoi.{join_cloumn} =tpli.parent 
		where tpo.name =%s
		order by tpoi.idx asc
	"""
	item_details=frappe.db.sql(sql,(packing_name,),as_dict=as_dict)

	head_sql="""
			SELECT tpp.name,tpp.customer ,tpp.customer_name ,tpp.currency ,tpp.posting_date ,
			tpp.customer_address , tpp.contact_person ,tpp.contact_phone ,tpp.incoterm,
			tpp.payment_term,tpp.invoice_no,tpp.customers_purchase_order,tpp.notify_party,tpp.remark,
			sum(tppi.net_weight_pkg) total_net_weight_pkg,sum(tppi.gross_weight_pkg) total_gross_weight_pkg,
			sum(tppi.qty) total_qty,sum(tppi.amount) total_amount,sum(tppi.packages_no) total_packages_no,sum(tppi.cbm) total_cbm,tpp.shipping_fee,tpp.order_total_amount
			FROM `tabPacking Process` tpp 
			left join `tabPacking Process Item` tppi on tpp.name = tppi.parent 
			where tpp.name=%s
			group by tpp.name,tpp.customer ,tpp.customer_name ,tpp.currency ,tpp.posting_date ,
			tpp.customer_address , tpp.contact_person ,tpp.contact_phone ,tpp.incoterm,
			tpp.payment_term,tpp.invoice_no,tpp.customers_purchase_order,tpp.notify_party,tpp.remark,tpp.shipping_fee,tpp.order_total_amount
	"""
	doc=frappe.db.sql(head_sql,(packing_name,),as_dict=as_dict)
	if doc:
		doc=doc[0]
		
	return  {"items":item_details,"doc":doc}

@frappe.whitelist()
def freeze_packing_process(name):
    #  doc=frappe.get_doc("Packing Process",name)
    #  doc.db_set("is_freeze",1)
    frappe.db.set_value("Packing Process",name,"is_freeze","1")



@frappe.whitelist()
def get_upaid_amount_total():
    res=frappe.get_all('Packing Process',filters={"is_settled":"0"},fields=['sum(order_total_amount-total_amount_paid) as amount'],limit=1)
    if res:
        return res[0].amount
    else:
        return 0